package com.google.code.mochaccino.framework.jaxws;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.common.base.Preconditions;
import com.sun.xml.ws.transport.http.servlet.ServletAdapter;
import com.sun.xml.ws.transport.http.servlet.ServletAdapterList;
import com.sun.xml.ws.transport.http.servlet.WSServlet;
import com.sun.xml.ws.transport.http.servlet.WSServletDelegate;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;

/**
 * JAXWS Servlet that do not use the servlet-config to load the configuration
 * for JAXWS services.
 */
public final class JaxwsServlet extends WSServlet {

	/** The Actual Definitions */
	private transient WSEndpointDefinition[] definitions;
	private transient WSEndpointFactory      factory;

	/** Constructor receiving the service definitions */
	public JaxwsServlet( WSEndpointFactory factory, WSEndpointDefinition[] definitions ) {
		super();
		this.factory = Preconditions.checkNotNull( factory );
		this.definitions = Preconditions.checkNotNull( definitions );
		Preconditions.checkArgument( definitions.length > 0 );
	}

	/** The Delegate */
	@Override
	protected WSServletDelegate getDelegate( ServletConfig servletConfig ) {
		List<ServletAdapter> adapterImplList = new ArrayList<ServletAdapter>();
		ServletAdapterList adapterList = new ServletAdapterList( servletConfig.getServletContext() );
		for ( WSEndpointDefinition d : definitions ) {
			if ( d.getWebService() != null ) {
				adapterImplList.add( adapterList.createAdapter( d.getWebService().name(), d.getPath(), factory.toEndpoint( d ) ) );
			}
		}
		return new WSServletDelegate( adapterImplList, servletConfig.getServletContext() );
	}
}
